package cn.sypt.yuhao.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;

import sun.misc.BASE64Encoder;
import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import cn.sypt.yuhao.dao.VideoDao;
import cn.sypt.yuhao.domain.Acategory;
import cn.sypt.yuhao.domain.Bcategory;
import cn.sypt.yuhao.domain.Category;
import cn.sypt.yuhao.domain.Comments;
import cn.sypt.yuhao.domain.Exam;
import cn.sypt.yuhao.domain.Reply;
import cn.sypt.yuhao.domain.Tip;
import cn.sypt.yuhao.domain.User;
import cn.sypt.yuhao.domain.Video;
import cn.sypt.yuhao.domain.Zan;
import cn.sypt.yuhao.model.JavaMail;
import cn.sypt.yuhao.model.UserBeanBO;
import cn.sypt.yuhao.pager.PageBean;

public class VideoServlet extends BaseServlet {
	private VideoDao vd = new VideoDao();

	
	public void tip(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String spname=request.getParameter("spname");
	//	System.out.println(spname);
		List<Tip> listdao=vd.tip(spname);
		JSONArray json=JSONArray.fromObject(listdao);
	//	System.out.println(json);
		response.getWriter().print(json);
	}
	// /一级分类
	public String findyifenlei(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Category> listcategory = vd.yijifenlei();
		List<Acategory> listacategory = vd.erjifenlei(listcategory.get(0)
				.getFid());
		List<Bcategory> listbcategory = vd.sanjifenlei(listacategory.get(0)
				.getAid());
		request.setAttribute("lista", listcategory);
		request.setAttribute("listb", listacategory);
		request.setAttribute("listc", listbcategory);
		return "f:/home/form.jsp";
	}

	public void finderfenlei(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String fid = request.getParameter("fid");
		List<Acategory> lista=vd.erjifenlei(fid);
		JSONArray jsona=JSONArray.fromObject(lista);
		response.getWriter().print(jsona);

	}

	public void findsanfenlei(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String aid = request.getParameter("aid");
		List<Bcategory> listb=vd.sanjifenlei(aid);
		JSONArray jsonb=JSONArray.fromObject(listb);
		response.getWriter().print(jsonb);
	}

	public String search(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String spname = request.getParameter("spname");

		List<Video> video = vd.search(spname);
		request.setAttribute("msg", spname);
		request.setAttribute("video", video);
		return "f:/ui/search.jsp";
	}

	public void searchInfo(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String spname = request.getParameter("spname");
		List<Video> video = vd.search(spname);
		JSONArray jsonarray = JSONArray.fromObject(video);
		response.getWriter().print(jsonarray);
	}

	public String findComment(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");

		List<Comments> comment = vd.findComment(user.getUid());
		request.setAttribute("comment", comment);
		return "f:/home/comment.jsp";
	}

	/**
	 * 查找回复内容
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findReply(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("cid");
		int count = Integer.parseInt(request.getParameter("count"));
		Comments comment = vd.findBycid(cid);
		List<Reply> listReply = vd.findReply(cid, count);
		request.setAttribute("listReply", listReply);
		request.setAttribute("comm", comment);
		return "f:/ui/reply.jsp";
	}

	/**
	 * 添加回复
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void addReply(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Reply reply = CommonUtils
				.toBean(request.getParameterMap(), Reply.class);
		reply.setRid(CommonUtils.uuid());
		reply.setRtime(getStringDate());
		vd.addReply(reply);
		response.getWriter()
				.print("<script language=javascript>self.location=document.referrer;</script>");
	}

	public void findByExam(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int nid = Integer.parseInt(request.getParameter("nid"));
		String spid = request.getParameter("spid");

		Exam exam = vd.findByExam(spid, nid);
		// System.out.println(exam.getTtm());
		// JSONArray jsonArray = JSONArray.fromObject(exam);
		JSONObject jsonexam = JSONObject.fromObject(exam);

		// System.out.println(jsonexam);
		response.getWriter().print(jsonexam);
	}

	/*
	 * 添加评论
	 */
	public void addComment(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Comments comment = CommonUtils.toBean(request.getParameterMap(),
				Comments.class);
		comment.setPtime(getStringDate());
		comment.setCid(CommonUtils.uuid());
		vd.addcomment(comment);
		response.getWriter()
				.print("<script language=javascript>self.location=document.referrer;</script>");
	}

	/**
	 * 查找单个视频
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findByspid(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String spid = request.getParameter("spid");
		HttpSession session = request.getSession();
		String uid = (String) session.getAttribute("uid");
		User user = (User) request.getSession().getAttribute("user");
		if (user != null) {
			List<Video> listtuijian = vd.findtuijian(user.getUid());
			request.setAttribute("tuijian", listtuijian);
		}
		Video video = vd.findByspid(spid, uid);

		if (video.getSpsh() == 2) {
			request.setAttribute("msg", "该实验已被删除！！");
			return "f:/admin/404.jsp";
		}
		if (video.getSpsh() == 0) {
			request.setAttribute("msg", "该实验还未审核通过，请稍后再查看！！");
			return "f:/admin/404.jsp";
		}
		Exam exam = vd.findByExam(spid, 0);
		video.setExam(exam);
		System.out.println("2" + video);
		request.setAttribute("video", video);
		return "f:/ui/single.jsp";
	}

	/**
	 * 后台查找单个视频
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findByadminspid(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String spid = request.getParameter("spid");
		String flag = request.getParameter("flag");
		String yjxx = request.getParameter("yjxx");
		if (flag != null) {
			if (yjxx != null) {
				String uname = request.getParameter("uname");
				UserBeanBO ubb = new UserBeanBO();
				String uemail = ubb.getUser(uname).getUemail();
				System.out.println(uname + "," + uemail + "," + yjxx);
				String to = uemail;// 发送对象，需要用户的邮箱....自己根据需要填写
				String subject = "来自高校实验学习平台视频审核邮件";// 的主题....自己根据需要填写
				String content = "您好 " + uname + "," + yjxx;// 的内容....自己根据需要填写
				JavaMail jm = new JavaMail();
				jm.send(to, subject, content);
			}
		}
		Video video = vd.findByadminspid(spid);
		request.setAttribute("video", video);
		return "f:/admin/single.jsp";
	}

	public void dianzan(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uid = request.getParameter("uid");
		String spid = request.getParameter("spid");
		String values = request.getParameter("value");
		int value = Integer.parseInt(values);
		String ztime = getStringDate();

		Zan zan = vd.findBysc(spid, uid);
		System.out.println("zan" + zan);
		String data;
		if (zan == null) {
			int spdz = vd.dianzan(uid, spid, ztime, value);
			data = spdz + "";
		} else {
			data = "";
		}
		// System.out.println("data数据"+data);
		response.getWriter().print(data);

	}

	public void updatedown(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String spid = request.getParameter("spid");
		int spxz = vd.updatedown(spid);
		String data = spxz + "";
		response.getWriter().print(data);
		// return null;
	}

	public String downloadfile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// System.out.println("downloadservlet");
		String uid = request.getParameter("uid");
		String spid = request.getParameter("spid");
		String spurl = request.getParameter("spwdurl");
		// ///////////////
		// System.out.println("uid"+uid);
		// System.out.println("spid"+spid);
		// System.out.println("spurl"+spurl);
		/*
		 * 两个头一个流 1. Content-Type 2. Content-Disposition 3. 流：下载文件的数据
		 */
		// 为了使下载框中显示中文文件名称不出乱码！
		String filename = this.getServletContext().getRealPath("/ui/file/")
				+ "//" + spurl;
		String framename = filenameEncoding(spurl, request);
		System.out.println(filename);
		String contentType = this.getServletContext().getMimeType(filename);// 通过文件名称获取MIME类型
		String contentDisposition = "attachment;filename=" + framename;
		// 一个流
		FileInputStream input = new FileInputStream(filename);

		// 设置头
		response.setHeader("Content-Type", contentType);
		response.setHeader("Content-Disposition", contentDisposition);

		// 获取绑定了响应端的流
		ServletOutputStream output = response.getOutputStream();

		IOUtils.copy(input, output);// 把输入流中的数据写入到输出流中。
		input.close();
		// ////////
		// vd.download(uid, spid);

		// response.getWriter().print(data);
		return null;

	}

	/**
	 * 视频下载
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String download(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("downloadservlet");
		String uid = request.getParameter("uid");
		String spid = request.getParameter("spid");
		String spurl = request.getParameter("spurl");
		// ///////////////
		System.out.println("uid" + uid);
		System.out.println("spid" + spid);
		System.out.println("spurl" + spurl);
		/*
		 * 两个头一个流 1. Content-Type 2. Content-Disposition 3. 流：下载文件的数据
		 */
		// 为了使下载框中显示中文文件名称不出乱码！
		String filename = this.getServletContext().getRealPath("/ui/video/")
				+ "//" + spurl;
		String framename = filenameEncoding(spurl, request);
		System.out.println(filename);
		String contentType = this.getServletContext().getMimeType(filename);// 通过文件名称获取MIME类型
		String contentDisposition = "attachment;filename=" + framename;
		// 一个流
		FileInputStream input = new FileInputStream(filename);

		// 设置头
		response.setHeader("Content-Type", contentType);
		response.setHeader("Content-Disposition", contentDisposition);

		// 获取绑定了响应端的流
		ServletOutputStream output = response.getOutputStream();

		IOUtils.copy(input, output);// 把输入流中的数据写入到输出流中。
		input.close();
		// ////////
		String xztime = getStringDate();
		vd.download(uid, spid, xztime);

		// response.getWriter().print("<script language=javascript>self.location=document.referrer;</script>");
		return null;
	}

	public String findBybid(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int pc = getPc(request);
		String url = getUrl(request);
		String bid = request.getParameter("bid");
		PageBean<Video> pb = (PageBean<Video>) vd.findBybid(pc, bid);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		return "f:/ui/products.jsp";

	}

	private int getPc(HttpServletRequest req) {
		int pc = 1;
		String param = req.getParameter("pc");
		if (param != null && !param.trim().isEmpty()) {
			try {
				pc = Integer.parseInt(param);
			} catch (RuntimeException e) {
			}
		}
		return pc;
	}

	/**
	 * 截取url，页面中的分页导航中需要使用它做为超链接的目标！
	 * 
	 * @param req
	 * @return
	 */

	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI() + "?" + req.getQueryString();
		/*
		 * 如果url中存在pc参数，截取掉，如果不存在那就不用截取。
		 */
		int index = url.lastIndexOf("&pc=");
		if (index != -1) {
			url = url.substring(0, index);
		}
		return url;
	}

	public static String filenameEncoding(String filename,
			HttpServletRequest request) throws IOException {
		String agent = request.getHeader("User-Agent"); // 获取浏览器
		if (agent.contains("Firefox")) {
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filename = "=?utf-8?B?"
					+ base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
		} else if (agent.contains("MSIE")) {
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}

	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = formatter.format(currentTime);
		return date;
	}
}
